import 'dart:async';
import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_bmflocation/bdmap_location_flutter_plugin.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:flutter_picker/PickerLocalizationsDelegate.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:provider/provider.dart';
import 'package:catcher/core/catcher.dart';

import 'package:flutter_bmfbase/BaiduMap/map/bmf_map_sdk.dart';
import 'package:jpush_flutter/jpush_flutter.dart';
import 'package:uni_links/uni_links.dart';
import 'package:flutter_bmfbase/BaiduMap/map/bmf_types.dart';

import 'package:loxen/dialog/show_policy_dialog.dart';
import 'package:loxen/mode/inspiration/inspiration_info_bean.dart';
import 'package:loxen/router_observer.dart';
import 'package:loxen/utils/save_util.dart';
import 'package:loxen/view/home/home_page.dart';
import 'package:loxen/view/login/login_code_page.dart';
import 'package:loxen/view/login/login_page.dart';
import 'package:loxen/view/login/registe_page.dart';
import 'package:loxen/viewmode/mine_notification_viewmodel.dart';
import 'package:loxen/routes/routes.dart';
import 'package:loxen/utils/config.dart';
import 'package:loxen/viewmode/login_view_model.dart';
import 'package:loxen/viewmode/theme_viewmodel.dart';
import 'package:sharesdk_plugin/sharesdk_interface.dart';
import 'package:sharesdk_plugin/sharesdk_plugin.dart';

void main() {
  Catcher(
    MyApp(),
    debugConfig: Constants.debugOptions,
    releaseConfig: Constants.releaseOptions,
  );
  if (Platform.isAndroid) {
    SystemUiOverlayStyle systemUiOverlayStyle = SystemUiOverlayStyle(
      statusBarColor: Colors.transparent,
      statusBarIconBrightness: Brightness.dark,
    );
    SystemChrome.setSystemUIOverlayStyle(systemUiOverlayStyle);
  }
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  void baiduInit() async {
    String strKey = 'iWF4NnagQhFrwuVoQEnqb0yRIYpyMvDk';
    if (Platform.isIOS) {
      BMFMapSDK.setApiKeyAndCoordType(strKey, BMF_COORD_TYPE.BD09LL);
      LocationFlutterPlugin.setApiKey(strKey);
    } else {
      BMFMapSDK.setCoordType(BMF_COORD_TYPE.BD09LL);
    }
  }

  void shareSdkInit() async {
    ShareSDKRegister register = ShareSDKRegister();
    register.setupWechat(
        "wx2a344c789a6462c6",
        "29d5e9d76ab63647a77e960bc74baed2",
        "https://ncc3i.share2dlink.com/"
    );
    register.setupSinaWeibo(
        "2531976281",
        "3b65035fa29b59c8a39611affb6ab733",
        "http://www.sharesdk.cn"
    );
    register.setupQQ("1110445396", "Py8TVwwtiGTcXOUU");
    SharesdkPlugin.regist(register);
  }

  submitPrivacyGrantResult() {
    SharesdkPlugin.uploadPrivacyPermissionStatus(1, (bool success) {
      if (success == true) {
        print('接入隐私协议授权提交结果-成功');
      } else {
        print('接入隐私协议授权提交结果-成功');
      }
    });
  }

  @override
  void initState() {
    super.initState();
    shareSdkInit();
    baiduInit();
    submitPrivacyGrantResult();
  }

  @override
  Widget build(BuildContext context) {
    return MultiProvider(
        providers: [
          ChangeNotifierProvider<LoginViewModel>(
            create: (_) {
              LoginViewModel model = LoginViewModel();
              return model;
            },
          ),
          ChangeNotifierProvider<ThemeViewModel>(
            create: (_) => ThemeViewModel(),
          ),
          ChangeNotifierProvider<MineNotificationViewModel>(
            create: (_) => MineNotificationViewModel(),
          )
        ],
        child: Consumer2<ThemeViewModel, LoginViewModel>(builder: (context, model1, model2, __) {
          model2.initUser();
          return MaterialApp(
            title: "LOXEN",
            onGenerateRoute: (settings) => Routes.configRoutes(settings),
            navigatorObservers: [routeObserver],
            localizationsDelegates: [
              PickerLocalizationsDelegate.delegate, //
              GlobalMaterialLocalizations.delegate,
              GlobalWidgetsLocalizations.delegate,
            ],
            debugShowCheckedModeBanner: false,
            routes: {
              Routes.main_page: (context) => HomePageWidget(),
              Routes.login_page: (context) => LoginPage(),
              Routes.login_code_page: (context) => LoginCodePage(),
              Routes.register: (context) => RegisterPage(),
            },
            supportedLocales: [
              const Locale('zh', 'ZH'),
              const Locale('en', 'EN'),
            ],
            theme: model1.themeData,
            home: MetricsReactor(),
          );
        }));
  }


}

class MetricsReactor extends StatefulWidget {
  @override
  _MetricsReactorState createState() => _MetricsReactorState();
}

class _MetricsReactorState extends State<MetricsReactor> {
  bool initData = false;
  StreamSubscription _sub;
  JPush jPush = JPush();
  
  @override
  void dispose() {
    super.dispose();
    if (_sub != null) _sub.cancel();
  }

  void showCupertinoDialog(BuildContext context) async {
    var data = await showDialog(context: context, builder: (_) => ShowPolicyDialog());
    if (data != null && data) {
      Navigator.of(context).popAndPushNamed(Routes.main_page);
      SharedPreferencesUtil.putData(Constants.agreePolicy, true);
    } else {
      SystemChannels.platform.invokeMethod('SystemNavigator.pop');
    }
  }

  void init() async {
    if (initData) return;
    initData = true;
    WidgetsBinding.instance.addPostFrameCallback((mag) async {
      var data = await SharedPreferencesUtil.getData(Constants.agreePolicy);
      if (data == null) {
        showCupertinoDialog(context);
      } else {
        Future.delayed(
            Duration(milliseconds: 500), () => Navigator.of(context).pushNamed(Routes.main_page));
      }
    });
  }

  void jPushInit() {
    jPush.setup(
      appKey: 'cc51e77fedc0c6cb15f6faa4',
      channel: "developer-default",
      production: false,
      debug: true,
    );
    jPush.applyPushAuthority(new NotificationSettingsIOS(sound: true, alert: true, badge: true));
    jPush.addEventHandler(
      // 接收消息通知后的回调
        onReceiveNotification: (Map<String, dynamic> message) async {
          Provider.of<MineNotificationViewModel>(context, listen: false).setNotification(true);
        },
        // 点击消息通知后的回调
        onOpenNotification: (Map<String, dynamic> message) async {
          Provider.of<MineNotificationViewModel>(context, listen: false).setNotification(false);
          Navigator.of(context).pushNamed(Routes.mineMsg);
          print(message);
        });
  }

  void schemeJump(BuildContext context, String schemeUrl) {
    final _jumpUri = Uri.parse(schemeUrl.replaceFirst(
      'loxen://',
      'http://path/',
    ));
    print('path${_jumpUri.path}');
    switch (_jumpUri.path) {
      case '/detail':
        InspirationInfo myWorks = InspirationInfo();
        myWorks.id = int.parse(_jumpUri.queryParameters['id'].toString());
        Future.delayed(Duration(milliseconds: 900), () {
          Navigator.of(context).pushNamed(Routes.inspiration_detail, arguments: myWorks);
        });
        break;
      default:
        break;
    }
  }

  Future<void> initPlatformState() async {
    String initialLink;
    try {
      initialLink = await getInitialLink();
      if (initialLink != null) {
        //  跳转到指定页面
        schemeJump(context, initialLink);
      }
    } on PlatformException {
      initialLink = 'Failed to get initial link.';
    } on FormatException {
      initialLink = 'Failed to parse the initial link as Uri.';
    }
    // Attach a listener to the links stream
    _sub = getLinksStream().listen((String link) {
      if (!mounted || link == null) return;
      //  跳转到指定页面
      schemeJump(context, link);
    }, onError: (Object err) {
      if (!mounted) return;
    });
  }

  void initState() {
    super.initState();
    initPlatformState();
    jPushInit();
  }

  @override
  Widget build(BuildContext context) {
    ScreenUtil.init(context, width: 750, height: 1334);
    init();
    return Container(
      child: Image.asset(
        'images/splash.png',
        fit: BoxFit.cover,
        width: double.infinity,
        height: double.infinity,
      ),
    );
  }
}
